﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Solar.Core;
using Application.Domain;
using System.Web;
using Solar.Security;
using Application.Service.Contract;

namespace Application.Service
{
    public class CustomerService
    {
        public const string AuthenticationType = "Application";

        #region Guest
        public GuestDto AddGuest()
        {
            using (var _repository = DomainRepository.Open())
            {
                var guest = new Guest
                {
                    Ip = HttpContext.Current.Request.UserHostAddress,
                    UserAgent = HttpContext.Current.Request.UserAgent
                };

                var newGuestId = _repository.Add(guest);

                return _repository.Get<Guest>(newGuestId).ExposedAs<GuestDto>();
            }
        }

        public GuestDto GetGuest(int id)
        {
            using (var _repository = DomainRepository.Open())
            {
                var guest = _repository.Get<Guest>(id);

                if (guest != null)
                {
                    return guest.ExposedAs<GuestDto>();
                }

                return new GuestDto();
            }
        }

        public bool ValidateGuest(int id)
        {
            using (var _repository = DomainRepository.Open())
            {
                var guest = _repository.Get<Guest>(id);
                return (guest != null);
            }
        }
        #endregion

        public IUserPrincipal Authenticate(string username, string password)
        {
            using (var repository = DomainRepository.Open())
            {
                var account = repository.GetOne<Account>(c => c.Username == username);

                if (account != null && account.Password.Equals(password))
                {
                    return new UserPrincipal(new UserIdentity(account.Id, account.Username, account.Username, AuthenticationType, true), this.GetRoles(username));
                }

                return UserPrincipal.Unidentified;
            }
        }

        private IEnumerable<string> GetRoles(string userId)
        {
            return new string[] { "Customers" }; // TODO: query roles
        }
    }
}
